import { useEffect } from 'react';
import { observer } from 'mobx-react';
import { runInAction,observe } from 'mobx';
import store from '@/store/public';
import { setItem,getItem } from '@/util';

let clienTimer = null;
let commonTimer = null;
function watchPageTabStatus(){
  //监听页面是否隐藏
  let timer = null;
  document.addEventListener('visibilitychange',e => {
    clearTimeout(timer)
    if(document.hidden){
      timer = setTimeout(()=>{
        runInAction(()=>{
          store.isPageTabShow = false;
        })
      },0.5 * 60 * 1000)
    }else{
      runInAction(()=>{
        store.isPageTabShow = true;
      })
    }
  },false)
}

function watchTheme() {
  // 监听主题变化
  setItem('theme',store.theme)
  document.querySelector('body').setAttribute('class',store.theme);
  observe(store,'theme',res => {
    document.querySelector('body').setAttribute('class',res.newValue);
  })
}

function handleWindowResize(){
  // 监听浏览器缩放
  clearTimeout(clienTimer);
  clienTimer = setTimeout(()=>{
    runInAction(() => {
      store.bodyWidth = window.innerWidth;
      store.bodyHeight = window.innerHeight;
    })
  },120)
}

function Common(){
  useEffect(() => {
     commonTimer= setTimeout(()=>{
      watchPageTabStatus();
      watchTheme();
    })
    return () => clearTimeout(commonTimer)
  }, [store.theme]);

  useEffect(() => {
    window.addEventListener("resize", handleWindowResize);
    return () => window.removeEventListener("resize", handleWindowResize);
  },[]);

	return (
		<></>
	)
}

export default observer(Common);